package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.base.BaseEntity;
import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.enums.TxnType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.system.domain.WdyBuyProduct;
import com.ruoyi.system.domain.WdyTxnHistory;
import com.ruoyi.system.domain.WdyUser;
import com.ruoyi.system.domain.WdyVcRelease;
import com.ruoyi.system.mapper.WdyVcReleaseMapper;
import com.ruoyi.system.service.IWdyBuyProductService;
import com.ruoyi.system.service.IWdyTxnHistoryService;
import com.ruoyi.system.service.IWdyUserService;
import com.ruoyi.system.service.IWdyVcReleaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * vc释放 服务层实现
 * 
 * @author ruoyi
 * @date 2019-12-16
 */
@Service
public class WdyVcReleaseServiceImpl extends ServiceImpl<WdyVcReleaseMapper, WdyVcRelease> implements IWdyVcReleaseService
{
	@Autowired
	private IWdyUserService wdyUserService;

	@Autowired
	private IWdyBuyProductService wdyBuyProductService;

	@Autowired
	private IWdyTxnHistoryService wdyTxnHistoryService;
	/**
     * 查询vc释放信息
     * 
     * @param id vc释放ID
     * @return vc释放信息
     */
    @Override
	public WdyVcRelease selectWdyVcReleaseById(Long id)
	{
	    return baseMapper.selectWdyVcReleaseById(id);
	}
	
	/**
     * 查询vc释放列表
     * 
     * @param wdyVcRelease vc释放信息
     * @return vc释放集合
     */
	@Override
	public List<WdyVcRelease> selectWdyVcReleaseList(WdyVcRelease wdyVcRelease)
	{
	    return baseMapper.selectWdyVcReleaseList(wdyVcRelease);
	}
	
    /**
     * 新增vc释放
     * 
     * @param wdyVcRelease vc释放信息
     * @return 结果
     */
	@Override
	public int insertWdyVcRelease(WdyVcRelease wdyVcRelease)
	{
	    return baseMapper.insertWdyVcRelease(wdyVcRelease);
	}
	
	/**
     * 修改vc释放
     * 
     * @param wdyVcRelease vc释放信息
     * @return 结果
     */
	@Override
	public int updateWdyVcRelease(WdyVcRelease wdyVcRelease)
	{
	    return baseMapper.updateWdyVcRelease(wdyVcRelease);
	}

	/**
     * 删除vc释放对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteWdyVcReleaseByIds(String ids)
	{
		return baseMapper.deleteWdyVcReleaseByIds(Convert.toStrArray(ids));
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public WdyBuyProduct release(WdyBuyProduct wdyBuyProduct, Date curDate) {
		BigDecimal releaseAmount = wdyBuyProduct.getReleaseAmount();
		if(wdyBuyProduct.getFreezeVcAmount().compareTo(releaseAmount) < 0) {
			releaseAmount = wdyBuyProduct.getFreezeVcAmount();
		}

		WdyVcRelease wdyVcRelease = new WdyVcRelease();
		wdyVcRelease.setUserId(wdyBuyProduct.getUserId());
		wdyVcRelease.setAmount(releaseAmount);
		wdyVcRelease.setTxnId(wdyBuyProduct.getId());
		this.save(wdyVcRelease);

		wdyBuyProduct.setFreezeVcAmount(BigDecimalUtil.subtract(wdyBuyProduct.getFreezeVcAmount(), releaseAmount));
		wdyBuyProductService.updateById(wdyBuyProduct);

		pick(wdyVcRelease, curDate);

		return wdyBuyProduct;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void pick(WdyVcRelease wdyVcRelease, Date curDate) {
		QueryWrapper<WdyUser> userQuery = new QueryWrapper<>();
		userQuery.eq("user_id", wdyVcRelease.getUserId());
		userQuery.eq("del_flag", BaseEntity.NOT_DELETED);
		WdyUser user = wdyUserService.getOne(userQuery);

		BigDecimal amount = wdyVcRelease.getAmount();
		BigDecimal vcConsumeAmount = BigDecimalUtil.getP2BigDecimal(BigDecimalUtil.multiply(amount, 0.3));
		BigDecimal vcWithdrawAmount = BigDecimalUtil.getP2BigDecimal(BigDecimalUtil.subtract(amount, vcConsumeAmount));

		WdyUser updateUser = new WdyUser();
		updateUser.setVcConsumeAmount(BigDecimalUtil.add(user.getVcConsumeAmount(), vcConsumeAmount));
		updateUser.setVcWithdrawAmount(BigDecimalUtil.add(user.getVcWithdrawAmount(), vcWithdrawAmount));
		updateUser.setVersion(user.getVersion());
		if(!wdyUserService.update(updateUser, userQuery)) {
			throw new BusinessException(ResultConstants.EX9110, "系统繁忙，请稍后重试");
		}

		WdyVcRelease updateRelease = new WdyVcRelease();
		updateRelease.setPickDay(curDate);
		updateRelease.setPickStatus(BaseEntity.YES);
		QueryWrapper<WdyVcRelease> updateReleaseQuery = new QueryWrapper<>();
		updateReleaseQuery.eq("id", wdyVcRelease.getId());
		updateReleaseQuery.eq("pick_status", BaseEntity.NO);
		if(!this.update(updateRelease, updateReleaseQuery)) {
			throw new BusinessException(ResultConstants.EX9110, "系统繁忙，请稍后重试");
		}

		WdyTxnHistory txnHistory = new WdyTxnHistory();
		txnHistory.setUserId(user.getUserId());
		txnHistory.setTxnId(String.valueOf(wdyVcRelease.getId()));
		txnHistory.setTxnAmount(vcConsumeAmount);
		txnHistory.setTxnType(TxnType.RELEASE_VC.getCode());
		txnHistory.setAmountType(TxnType.RELEASE_VC.getAmountType().getCode());
		txnHistory.setTxnDesc(TxnType.RELEASE_VC.getName());
		wdyTxnHistoryService.save(txnHistory);

		txnHistory = new WdyTxnHistory();
		txnHistory.setUserId(user.getUserId());
		txnHistory.setTxnId(String.valueOf(wdyVcRelease.getId()));
		txnHistory.setTxnAmount(vcWithdrawAmount);
		txnHistory.setTxnType(TxnType.RELEASE_VC_WITHDRAW.getCode());
		txnHistory.setAmountType(TxnType.RELEASE_VC_WITHDRAW.getAmountType().getCode());
		txnHistory.setTxnDesc(TxnType.RELEASE_VC_WITHDRAW.getName());

		wdyTxnHistoryService.save(txnHistory);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void pickVcAll(String userId) {
		QueryWrapper<WdyVcRelease> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", userId);
		queryWrapper.eq("pick_status", BaseEntity.NO);
		List<WdyVcRelease> list = this.list(queryWrapper);
		if(!CollectionUtils.isEmpty(list)) {
			Date curDate = new Date();
			list.forEach(e -> {
				pick(e, curDate);
			});
		}
	}

	@Override
	public BigDecimal getSum(WdyVcRelease wdyVcRelease) {
		return baseMapper.getSum(wdyVcRelease);
	}
}
